package com.zm.demo.core.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.lang.System.out;

/**
 *  前 K 个高频元素
 * @author zoum
 * @create 2020/1/9 15:16
 */
public class TopKFrequent {


    public List<Integer> topKFrequent(int[] nums, int k) {
        if (nums == null){
            return null;
        }
        if (nums.length == 0){
            return null;
        }
        if (nums.length == 1){
            return Arrays.asList(nums[0]);
        }

        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.compute(nums[i], (key, v) -> v == null ? 1 : v + 1);
        }

        return map.entrySet().parallelStream()
                .sorted((o1, o2) -> o2.getValue() > o1.getValue() ? 1 : (o2.getValue() == o1.getValue() ? 0 : -1))
                .limit(k).map(o->o.getKey()).collect(Collectors.toList());
    }

    public static void main(String[]args){
        out.println(new TopKFrequent().topKFrequent(null, 1));
    }
}
